// 储值卡工具类
// import {Message} from 'element-ui'
import store from '../store'

const dcrf32 = require('./dcrf32').Dcrf32
// const ref = require('ref-napi')
const iconv = require('iconv-lite')

const defaultKeyAHex = Buffer.from('FFFFFFFFFFFF')
// const sanshanKeyAHex = Buffer.from('F1F9F9F2F0F2')
const sanshanKeyBHex = Buffer.from('F0F1F2F2F3F8')
const sanshanPasswordHex = Buffer.from('f1f9f9f2f0f208778f69f0f1f2f2f3f8')
const defalutKeyHex = Buffer.from('FFFFFFFFFFFFFF078069FFFFFFFFFFFF')
const emptyCardHex = Buffer.from('F0000000000000000000000000000000')
// const defaultSection = 2 // 使用的扇区
const keySetA = 0 // 认证keya
const keySetB = 4 // 认证keyb

// 油站-扇区映射map
const stationSectionMap = new Map()
// 西鹏站使用扇区2
stationSectionMap.set(1, 2)
// 测试站使用扇区5
stationSectionMap.set(2, 5)
// 官井头使用扇区5
stationSectionMap.set(3, 5)

// 根据所属油站ID获取对应的扇区
function getSectionByStationId () {
  let stationId = store.getters.stationId
  let tmpSection = stationSectionMap.get(stationId)
  return tmpSection || 2
}

// 循环获取可用的扇区，从前面的油站使用扇区配置中循环
function getSection () {
  let values = Array.from(new Set(stationSectionMap.values()))
  for (var i = 0; i < values.length; i++) {
    console.log('try' + values[i])
    var snrBuffer = Buffer.alloc(16)
    var icDevice = dcrf32.dc_init(100, 115200)
    dcrf32.dc_reset(icDevice, 1)
    var st = dcrf32.dc_card(icDevice, 0, snrBuffer)
    if (st !== 0) {
      dcrf32.dc_exit(icDevice)
      continue
    }
    st = dcrf32.dc_authentication_passaddr_hex(icDevice, keySetB, values[i] * 4, sanshanKeyBHex)
    if (st !== 0) {
      console.log('dc_authentication_passaddr_hex fail')
      dcrf32.dc_exit(icDevice)
      continue
    }
    dcrf32.dc_exit(icDevice)
    console.log('return' + values[i])
    return values[i]
  }
  return '找不到可用扇区'
}

/**
 * 判断读卡器上是否有卡
 * @returns boolean
 */
export function isCardOnCardReader () {
  var cardNo = readCardNo()
  return !!cardNo
}

/**
 * 判断卡号是否是新卡
 * @param {*} cardNo
 * @returns boolean
 */
export function isNewCard (cardNo) {
  return cardNo === 'F00000000000'
}

/**
 * 判断当前卡是否为有效卡
 * 也就是判断密钥是否匹配
 */
export function isValidCard () {
  let section = getSectionByStationId()
  if (isNaN(section)) {
    return 'no valid section by stationId'
  }
  var snrBuffer = Buffer.alloc(16)
  var icDevice = dcrf32.dc_init(100, 115200)
  dcrf32.dc_reset(icDevice, 1)
  var st = dcrf32.dc_card(icDevice, 0, snrBuffer)
  if (st !== 0) {
    dcrf32.dc_exit(icDevice)
    return '读取不到卡片'
  }
  st = dcrf32.dc_authentication_passaddr_hex(icDevice, keySetB, section * 4, sanshanKeyBHex)
  if (st !== 0) {
    console.log('dc_authentication_passaddr_hex fail')
    dcrf32.dc_exit(icDevice)
    return '不是合法的卡片，尚未初始化或非法卡片'
  }
  dcrf32.dc_exit(icDevice)
  return ''
}

// 是否为新的空白卡
export function isNewEmptyCard () {
  let section = getSectionByStationId()
  if (isNaN(section)) {
    return 'no valid section by stationId'
  } else {
    console.log(section)
  }
  var snrBuffer = Buffer.alloc(16)
  var icDevice = dcrf32.dc_init(100, 115200)
  dcrf32.dc_reset(icDevice, 1)
  var st = dcrf32.dc_card(icDevice, 0, snrBuffer)
  if (st !== 0) {
    dcrf32.dc_exit(icDevice)
    return '读取不到卡片'
  }
  st = dcrf32.dc_authentication_passaddr_hex(icDevice, keySetA, section * 4, defaultKeyAHex)
  if (st !== 0) {
    console.log('dc_authentication_passaddr_hex fail')
    dcrf32.dc_exit(icDevice)
    return '不是合法的空白卡片'
  }
  dcrf32.dc_exit(icDevice)
  return ''
}

/**
 * 判断卡片是否为空白卡
 */
export function isEmptyCard () {
  var err = isValidCard()
  if (err) {
    cardReaderBeep()
    return false
  }
  // 读出卡号，判断卡号是否值为 F00000000000
  var cardNo = readCardNo()
  return cardNo && cardNo === 'F00000000000'
}

/**
 * 读取卡编号
 * @returns
 */
export function readCardNo () {
  console.log(getSection())
  let section = getSection()
  if (isNaN(section)) {
    return false
  }
  let snrBuffer = Buffer.alloc(100)
  let dataBuffer = Buffer.alloc(100)
  let icDevice = dcrf32.dc_init(100, 115200)
  if (icDevice < 0) {
    console.log('读卡器尚未连接')
    return false
  }
  var st = dcrf32.dc_reset(icDevice, 1)
  if (st !== 0) {
    console.log('dc_reset fail')
    dcrf32.dc_exit(icDevice)
    return false
  }
  st = dcrf32.dc_card(icDevice, 0, snrBuffer)
  if (st !== 0) {
    console.log('dc_card fail')
    dcrf32.dc_exit(icDevice)
    return false
  }
  st = dcrf32.dc_authentication_passaddr_hex(icDevice, keySetB, section * 4, sanshanKeyBHex)
  if (st !== 0) {
    console.log('dc_authentication fail')
    dcrf32.dc_exit(icDevice)
    return false
  }
  st = dcrf32.dc_read(icDevice, section * 4, dataBuffer)
  if (st !== 0) {
    console.log('dc_read fail')
    dcrf32.dc_exit(icDevice)
    return false
  }
  var hexBuffer = Buffer.alloc(100)
  st = dcrf32.hex_a(dataBuffer, hexBuffer, 32)
  if (st !== 0) {
    console.log('hex_a fail')
    dcrf32.dc_exit(icDevice)
    return false
  }
  dcrf32.dc_beep(icDevice, 10)
  dcrf32.dc_exit(icDevice)
  var oArr = iconv.decode(hexBuffer, 'GBK').split('')
  var cardNumber = ''
  for (var i = 0; i < 12; i++) {
    cardNumber += oArr[i]
  }

  console.log(cardNumber)
  return cardNumber
}

/**
 * 初始化卡，也就是把卡密钥写到M1的认证密钥块中
 * 扇区2区块3
 */
export function initCard () {
  let section = getSectionByStationId()
  var snrBuffer = Buffer.alloc(16)
  var icDevice = dcrf32.dc_init(100, 115200)
  dcrf32.dc_reset(icDevice, 1)
  var st = dcrf32.dc_card(icDevice, 0, snrBuffer)
  st = dcrf32.dc_authentication_passaddr_hex(icDevice, keySetA, section * 4, defaultKeyAHex)
  if (st !== 0) {
    console.log('dc_authentication fail')
    dcrf32.dc_exit(icDevice)
    return 'auth fail'
  }
  st = changeControlKey(icDevice)
  if (st) {
    return 'changeControlKey fail'
  }
  initEmptyData(icDevice)
  dcrf32.dc_beep(icDevice, 10)
  dcrf32.dc_exit(icDevice)
  return ''
}

function changeControlKey (icDevice) {
  let section = getSectionByStationId()
  var st = dcrf32.dc_write_hex(icDevice, section * 4 + 3, sanshanPasswordHex)
  if (st !== 0) {
    console.log('changeControlKey fail')
    dcrf32.dc_exit(icDevice)
    return 'changeControlKey fail'
  }
  return ''
}

// 设置初始化数据
function initEmptyData (icDevice) {
  let section = getSectionByStationId()
  var st = dcrf32.dc_authentication_passaddr_hex(icDevice, keySetB, section * 4, sanshanKeyBHex)
  if (st !== 0) {
    console.log('dc_authentication fail')
    dcrf32.dc_exit(icDevice)
    return 'dc_authentication fail'
  }
  st = dcrf32.dc_write_hex(icDevice, section * 4, emptyCardHex)
  if (st !== 0) {
    console.log('dc_write fail')
    dcrf32.dc_exit(icDevice)
    return 'dc_write fail'
  }
  return ''
}

/**
 * 擦除卡里面的卡号相关信息
 * 也就是把对应块的内容重置为0
 */
export function resetCard () {
  let section = getSectionByStationId()
  if (isNaN(section)) {
    return 'no valid section by stationId'
  }
  var snrBuffer = Buffer.alloc(16)
  var icDevice = dcrf32.dc_init(100, 115200)
  dcrf32.dc_reset(icDevice, 1)
  var st = dcrf32.dc_card(icDevice, 0, snrBuffer)
  if (st !== 0) {
    dcrf32.dc_exit(icDevice)
    return 'dc_card error'
  }
  st = dcrf32.dc_authentication_passaddr_hex(icDevice, keySetB, section * 4, sanshanKeyBHex)
  if (st !== 0) {
    console.log('dc_authentication fail')
    dcrf32.dc_exit(icDevice)
    return 'dc_authentication fail'
  }
  st = dcrf32.dc_write_hex(icDevice, section * 4 + 3, defalutKeyHex)
  if (st !== 0) {
    console.log('dc_write fail')
    dcrf32.dc_exit(icDevice)
    return 'write fail'
  }
  dcrf32.dc_exit(icDevice)
  return ''
}

/**
 * 写入卡号
 * @param {*} cardNo
 * @returns
 */
export function writeCardNo (cardNo) {
  console.log(cardNo)
  if (cardNo.length !== 12) {
    return '卡长度必须是12位'
  }
  // 判断卡是否有效且为空白卡
  var empty = isEmptyCard()
  if (!empty) {
    return '该卡不是空白卡'
  }
  let section = getSectionByStationId()
  if (isNaN(section)) {
    return 'no valid section by stationId'
  }
  var cardNoBuffer = Buffer.from(cardNo + '0'.repeat(20))
  var snrBuffer = Buffer.alloc(32)
  var icDevice = dcrf32.dc_init(100, 115200)
  dcrf32.dc_reset(icDevice, 1)
  var st = dcrf32.dc_card(icDevice, 0, snrBuffer)
  if (st !== 0) {
    console.log('dc_card fail')
    dcrf32.dc_exit(icDevice)
    return 'dc_card fail'
  }
  st = dcrf32.dc_authentication_passaddr_hex(icDevice, keySetB, section * 4, sanshanKeyBHex)
  if (st !== 0) {
    console.log('dc_authentication fail')
    dcrf32.dc_exit(icDevice)
    return 'dc_authentication fail'
  }
  st = dcrf32.dc_write_hex(icDevice, section * 4, cardNoBuffer)
  if (st !== 0) {
    console.log('dc_write fail')
    dcrf32.dc_exit(icDevice)
    return 'dc_write fail'
  }
  dcrf32.dc_exit(icDevice)
  return 'success'
}

/**
 * 判断读卡器是否连接正常
 * @returns boolean
 */
export function isCardReaderReady () {
  var icDevice = dcrf32.dc_init(100, 115200)
  dcrf32.dc_exit(icDevice)
  // console.log(icDevice)
  return icDevice && icDevice > 0
}

/**
 * 读卡器发出声音
 */
export function cardReaderBeep () {
  var icDevice = dcrf32.dc_init(100, 115200)
  dcrf32.dc_beep(icDevice, 10)
  dcrf32.dc_exit(icDevice)
}
